<?php

namespace App\Http\Controllers;

use App\Models\Topic;
use App\Models\TranslateImprovedRecord;
use App\Models\TranslateRecord;
use App\Models\TranslateSection;
use App\Services\TranslateService;
use Carbon\Carbon;
use Auth;
use Illuminate\Http\Request;
use App\Http\Requests\AdminTranslateRequest;

class AdminTranslateController extends Controller
{
    protected $translateService;

    public function __construct(TranslateService $translateService)
    {
        $this->translateService = $translateService;
    }

    /**
     * 翻译record的列表页
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
//        $query = Topic::query()
//            ->where('category_id', config('phphub.translate_id'))
//            ->orderBy('id', 'desc');
//
//        if (!empty($request->translate_status)) {
//            $query->where('translate_status', $request->translate_status);
//        }

//        $translates = $query->paginate();

        $query = TranslateRecord::query()->with('translateImprovedRecords')->orderBy('id', 'desc');

        if (!empty($request->status))
        {
            $query->where('status', $request->status);
        }

        $records = $query->paginate(50);

        return view('translate.admin.index', compact('records'));
    }

    public function drafts()
    {
        $query = Topic::query()
            ->where('category_id', config('phphub.translate_id'))
            ->where(['is_draft' => 'yes'])
            ->orderBy('id', 'desc');


        $topics = $query->paginate(20);

        return view('translate.admin.index', compact('topics'));
    }

    /**
     * 添加翻译
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $topic = new Topic();
        return view('translate.admin.create_edit', compact('topic'));
    }


    /**
     * 保存添加的翻译
     * @param AdminTranslateRequest $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function store(AdminTranslateRequest $request)
    {
        if ($request->subject == 'draft') {
            $data['is_draft'] = 'yes';
        }
        $data['title'] = $request->title;
        $data['original_url'] = $request->original_url;
        $data['body_original'] = $request->body_original;

        $this->translateService->create($data);

        return redirect(route('admin-translate.index'));
    }

    /**
     * 显示翻译帖子(暂时留着)
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $topic = Topic::findOrfail($id);
        if ($topic->category_id !== config('phphub.translate_id')) {

        }

        return view('translate.admin.create_edit', compact('topic'));
    }

    /**
     * 编辑添加的翻译
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $topic = Topic::with('translateSections')->findOrfail($id);

        return view('translate.admin.create_edit', compact('topic'));
    }

    /**
     * 更新添加的翻译
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //分段
        $data['is_draft'] = 'no';
        if ($request->subject == 'draft') {
            $data['is_draft'] = 'yes';
        }
        $data['title'] = $request->title;
        $data['original_url'] = $request->original_url;
        $data['body_original'] = $request->body_original;
        $this->translateService->update($id,$data);

        return redirect(route('topics.show', ['id' => $id]));

    }

    /**
     * 删除添加的翻译
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }


    /*******************审核相关********************/
    /**
     * 显示翻译的单个record
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showRecord($record_id, $improved_flag)
    {
        //改进的record
        if($improved_flag == 1)
        {
            $improved_record_id = $record_id;
            $improved_record = TranslateImprovedRecord::where('id', $improved_record_id)->firstOrFail();
            $record_id = $improved_record->translate_record_id;
        }

        $record = TranslateRecord::where('id', $record_id)->firstOrFail();

        $section = $record->translateSection;

        $topic = $section->topic;

        $data = compact('record','topic','section','improved_flag');
        if($improved_flag == 1)
        {
            $data = compact('improved_record','topic','section','improved_flag');
        }

        return view('translate.admin.show_record',$data);

    }


    public function audit(Request $request)
    {
        $params = $request->all();
        $improved_flag = $params['improved_flag'];
        $attr['status'] = $params['rdo_audit'];
        $attr['auditor'] = \Auth::user()->name;
        if($improved_flag == 0)
        {
            $translate_record = TranslateRecord::where('id', $params['record_id'])->firstOrFail();
            //更新审核通过与否状态
            $translate_record->setAttributes($attr);

            //如果审核通过
            if($params['rdo_audit'] == TranslateRecord::STATUS_AUDIT_PASS)
            {
                $translator_ids = $translate_record->translateSection->getAttrbute('translator_ids');
                if(!$translator_ids)
                {
                    $translator_ids = $translate_record->translator_id;
                }
                else
                {
                    if(!in_array($translate_record->translator_id, explode('-', $translator_ids)))
                    {
                        $translator_ids = $translator_ids . '-' . $translate_record->translator_id;
                    }
                }
                //更新本section的翻译人员id
                $translate_record->translateSection
                    ->setAttributes(['translator_ids' => $translator_ids,
                        'updated_at' => Carbon::now()]);
            }
            //如果确定作为本段的最终译文
            if(isset($params['chkbox_select']) && count($params['chkbox_select']) > 0)
            {
                //更新section的译文
                $section_data = ['translate_record_id' => $translate_record->id,
                    'translate_text' => $translate_record->translate_text,
                    'is_translated' => TranslateSection::IS_TRANSLATED,
                    'updated_at' => Carbon::now()];

                $this->translateService->updateSectionData($translate_record->translateSection->id,
                    $translate_record->translate_text, $section_data);

                $topic_id = $translate_record->translateSection->topic_id;
                //
                //如果topic已全部翻译完
                if($this->translateService->unTranslatedCount($topic_id) <= 0)
                {
                    $trans_sec_list = $this->translateService->getTranslatedSections($topic_id);
                    $topic_trans_text = '';
                    foreach ($trans_sec_list AS $section)
                    {
                        $topic_trans_text = $topic_trans_text . $section->translate_text;
                    }
                    //更新topic数据
                    $this->translateService->updateTopicData($topic_id, Topic::IS_TRANSLATED, $topic_trans_text);
                }
            }
        }
        elseif($improved_flag == 1)
        {
            $improved_record = TranslateImprovedRecord::where('id', $params['improved_record_id'])->firstOrFail();
            //更新审核通过与否状态
            $improved_record->setAttributes($attr);
            //如果审核通过
            if($params['rdo_audit'] == TranslateImprovedRecord::STATUS_AUDIT_PASS)
            {
                $translator_ids = $improved_record->translateRecord->translateSection->getAttrbute('translator_ids');
                if(!$translator_ids)
                {
                    $translator_ids = $improved_record->translator_id;
                }
                else
                {
                    if(!in_array($improved_record->translator_id, explode('-', $translator_ids)))
                    {
                        $translator_ids = $translator_ids . '-' . $improved_record->translator_id;
                    }
                }
                //更新本section的翻译人员id
                $improved_record->translateRecord->translateSection
                    ->setAttributes(['translator_ids' => $translator_ids,
                        'updated_at' => Carbon::now()]);

                //更新相应record改进翻译人员
                $improved_user_ids = $improved_record->translateRecord->getAttrbute('improved_user_ids');
                if(!$improved_user_ids)
                {
                    $improved_user_ids = $improved_record->translator_id;
                }
                else
                {
                    if(!in_array($improved_record->translator_id, explode('-', $improved_user_ids)))
                    {
                        $improved_user_ids = $improved_user_ids . '-' . $improved_record->translator_id;
                    }
                }
                //更新本section的翻译人员id
                $improved_record->translateRecord
                    ->setAttributes(['improved_user_ids' => $improved_user_ids,
                        'updated_at' => Carbon::now()]);

                //如果改进译文确定作为本段的最终译文
                if(isset($params['chkbox_select']) && count($params['chkbox_select']) > 0)
                {
                    //更新record的译文
                    $record_data = ['improved_record_id' => $improved_record->id,
                                    'translate_text' => $improved_record->translate_text];
                    $this->translateService->updateRecordData($improved_record->translateRecord->id, $record_data);
                    //更新section的译文
                    $section_data = ['translate_record_id' => $improved_record->translateRecord->id,
                        'translate_text' => $improved_record->translate_text,
                        'updated_at' => Carbon::now()];

                    $this->translateService->updateSectionData($improved_record->translateRecord->translateSection->id,
                        $improved_record->translate_text, $section_data);

                    //dd($improved_record->translate_imporved_text . "\r\n". $improved_record->translateRecord->translate_text . "\r\n".$improved_record->translateRecord->translateSection->translate_text);

                    $topic_id = $improved_record->translateRecord->translateSection->topic_id;
                    //
                    //如果topic已全部翻译完
                    if($this->translateService->unTranslatedCount($topic_id) <= 0)
                    {
                        $trans_sec_list = $this->translateService->getTranslatedSections($topic_id);
                        $topic_trans_text = '';
                        foreach ($trans_sec_list AS $section)
                        {
                            $topic_trans_text = $topic_trans_text . $section->translate_text;
                        }
                        //更新topic数据
                        $this->translateService->updateTopicData($topic_id, Topic::IS_TRANSLATED, $topic_trans_text);
                    }
                }

            }
        }



        return redirect()->route('admin-translate.index');
    }

}
